package org.lanqiao.api;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.lanqiao.entity.WebSocket;
import org.lanqiao.util.SpringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;

/**
 * @author 李静
 * @describe
 * @data
 */
@Slf4j
@ServerEndpoint("/websocket/{name}")
@Controller
public class WebSocketServer {

    /**
     * 因为@ServerEndpoint不支持注入，所以使用SpringUtils获取IOC实例
     */
    private StringRedisTemplate redisTampate = SpringUtils.getBean(StringRedisTemplate.class);

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //创建一个线程安全的map
    private static Map<String, WebSocketServer> users = Collections.synchronizedMap(new HashMap());
    //用来封装数据
    private static List<WebSocket> list = new ArrayList<>();
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    //放入map中的key,用来表示该连接对象
    private String username;
    //存放接收的数据
    private String jsonlist = null;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("name") String name) {
        System.out.println("当前session：" + session + "，用户:" + name + "连接WebSocket成功");
        this.session = session;
        this.username = name;
        users.put(username, this);   //加入map中,为了测试方便使用username做key
        addOnlineCount();           //在线数加1
        System.out.println("当前人数为：" + getOnlineCount());
        log.info(username + "加入！当前在线人数为" + getOnlineCount());


    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        users.remove(this.username);  //从set中删除
        subOnlineCount();           //在线数减1
        log.info("一个连接关闭！当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后触发的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message) {
        System.out.println("接受来自客户端的数据：" + message);
        log.info("来自客户端的消息:" + message);
        //拿到消息切割并存入redis
        addRedis(message);

    }


    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误 session: " + session);
        error.printStackTrace();
    }

    /**
     * 群发自定义消息
     */
    public void sendInfo(String message) throws IOException {
        for (WebSocketServer item : users.values()) {
            try {
                item.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

    //将用户的发送的消息进行全部推送
    private void addRedis(String message) {
        String[] split = message.split("-");
        //切割消息并进行封装
        WebSocket socket = new WebSocket();
        socket.setUserId(split[0]);
        socket.setActiveId(split[1]);
        socket.setImageUrl(split[2]);
        socket.setMsg(split[3]);
        list.add(socket);

        //将list集合转为json字符串
        ObjectMapper mapper = new ObjectMapper();

        try {
            jsonlist = mapper.writeValueAsString(list);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //打印json字符串
        System.out.println(jsonlist);
        //存入redis
        redisTampate.opsForValue().set("111", jsonlist);
        try {
            if (StringUtils.isEmpty(message)) {
                return;
            }
            System.out.println(redisTampate.opsForValue().get("111"));
            //给所有连接成功的用户推送json字符串数
            sendInfo(redisTampate.opsForValue().get("111"));

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    //该方法用来记录房间人数+1
    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    //该方法用来记录房间人数-1
    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}
